package com.itwanyan.m3u8loaderbypublic.dbdata;

import android.content.ContentValues;
import android.os.Environment;

import com.itwanyan.m3u8loaderbypublic.core.DownloadState;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created on 2018/4/26 10:17.
 *
 * @author ares
 */

public class DefaultDownloadHistoryDBHelper extends AbsDownloadHistoryDBHelper {

    public static  final String  saveVieoPath  = Environment.getExternalStorageDirectory().getPath() + File.separator + "gkbb/video/";
    private ExecutorService threadPool = Executors.newFixedThreadPool(10);
    /**
     * 初始化openhelper
     */
    public DefaultDownloadHistoryDBHelper() {
    }

    /********************数据处理start********************/
    public List<TsFileLoadRecord> getLoadTsFiles(String videoId) {
        List<TsFileLoadRecord> loadTsFiles = DataSupport.where("videoId = ?",
                videoId)
                .find(TsFileLoadRecord.class);
        return loadTsFiles;
    }

    public int getLoadTsFilesCount(String videoId) {
        int count = DataSupport.where("videoId = ?  and finishState = ?",
                videoId, String.valueOf(1))
                .count(TsFileLoadRecord.class);
        return count;
    }
    public void saveLoadTsFile(TsFileLoadRecord tsFileLoadRecord) {
        boolean isExist = DataSupport.isExist(TsFileLoadRecord.class, "fileName = ?",
                tsFileLoadRecord.getFileName());
        if (!isExist)
            tsFileLoadRecord.save();
        else {
            //需要更新一下Url
            ContentValues values = new ContentValues();
            values.put("basePath", tsFileLoadRecord.getBasePath());
//            DataSupport.updateAll(TsFileLoadRecord.class, values, "videoId=?", loadRecordBean.getVideoId());
//            values.put("loadUrl",loadRecordBean.getLoadUrl());
            DataSupport.updateAll(TsFileLoadRecord.class, values, "fileName=?", tsFileLoadRecord.getFileName());
        }
    }

    public void deleteLoadTsFiles(String videoId) {
        DataSupport.deleteAll(TsFileLoadRecord.class, "videoId = ? ", videoId);
    }

    public void updateTsFileLoadLenth(String fileName, long length) {
        ContentValues values = new ContentValues();
        values.put("loadLength", length);
        DataSupport.updateAll(TsFileLoadRecord.class, values, "fileName=?", fileName);
    }

    public void updateTsFileLoadState(String fileName, boolean finishState) {
        ContentValues values = new ContentValues();
        values.put("finishState", finishState);
        DataSupport.updateAll(TsFileLoadRecord.class, values, "fileName=?", fileName);
    }
    public boolean getTsFileLoadState(String fileName) {
        List<TsFileLoadRecord> loadM3u8Files = DataSupport.select("finishState").where("fileName = ?",
                fileName)
                .find(TsFileLoadRecord.class);
        if (loadM3u8Files.size() > 0)
            return  loadM3u8Files.get(0).isFinishState() ;
        return  false;
    }
    public List<LoadRecordBean> getLoadM3u8Files(String videoId) {
        List<LoadRecordBean> loadM3u8Files = DataSupport.where("videoId = ?",
                videoId)
                .find(LoadRecordBean.class);
        return loadM3u8Files;
    }
    public List<LoadRecordBean> getUnFinishLoadM3u8Files() {
        List<LoadRecordBean> loadM3u8Files = DataSupport.select("videoId", "loadUrl","totalTsCount","fileLength","loadTsCount","finishState")
                .where(" finishState !=?", String.valueOf(DownloadState.FINISH))
                .find(LoadRecordBean.class);
        return loadM3u8Files;
    }
    public List<LoadRecordBean> getFinishedLoadM3u8Files() {
        List<LoadRecordBean> loadM3u8Files = DataSupport.select("videoId", "loadUrl","videoName")
                .where("finishState =?", String.valueOf(DownloadState.FINISH))
                .find(LoadRecordBean.class);
        return loadM3u8Files;
    }

    public long getLoadM3u8FileLenth(String videoId) {//通过已下载文件的个数来判断下载的对的进度
        long loadFileLength = 0;
        List<LoadRecordBean> loadM3u8Files = DataSupport.where("videoId = ?",
                videoId)
                .find(LoadRecordBean.class);
        if (loadM3u8Files.size() > 0) {
            LoadRecordBean loadRecordBean = loadM3u8Files.get(0);
            loadFileLength = (loadRecordBean.getFileLength() / loadRecordBean.getTotalTsCount()) * loadRecordBean.getLoadTsCount();
        }
        return loadFileLength;
    }

    public void saveLoadM3u8File(LoadRecordBean loadRecordBean) {
        boolean isExist = DataSupport.isExist(LoadRecordBean.class, "videoId = ?",
                loadRecordBean.getVideoId());
        if (!isExist)
            loadRecordBean.save();
        else {
            //需要更新一下Url
            ContentValues values = new ContentValues();
            values.put("basePath", loadRecordBean.getBasePath());
            DataSupport.updateAll(TsFileLoadRecord.class, values, "videoId=?", loadRecordBean.getVideoId());
            values.put("loadUrl",loadRecordBean.getLoadUrl());
            values.put("finishState",loadRecordBean.getFinishState());
            DataSupport.updateAll(LoadRecordBean.class, values, "videoId=?", loadRecordBean.getVideoId());
        }

    }

    public void deleteLoadM3u8File(final String videoId) {

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                DataSupport.deleteAll(LoadRecordBean.class, "videoId = ? ", videoId);
                DataSupport.deleteAll(TsFileLoadRecord.class, "videoId = ? ", videoId);
                //同时删除文件
                String loadFileDir = saveVieoPath + videoId;
                File file = new File(loadFileDir);
                if (file.exists())
                    file.delete();
            }
        });
    }

    public void setM3u8FileLength(String videoId, long totalLength) {
        List<LoadRecordBean> loadM3u8Files = DataSupport.where("videoId = ?",
                videoId)
                .find(LoadRecordBean.class);
        if (loadM3u8Files.size() > 0) {
            ContentValues values = new ContentValues();
            values.put("fileLength", totalLength);
            DataSupport.updateAll(LoadRecordBean.class, values, "videoId=?", videoId);
        }
    }
    public void setM3u8FileBySingleLength(String videoId, long singleLength) {
        List<LoadRecordBean> loadM3u8Files = DataSupport.where("videoId = ?",
                videoId)
                .find(LoadRecordBean.class);
        if (loadM3u8Files.size() > 0) {
            int totalCount = loadM3u8Files.get(0).getTotalTsCount();
            ContentValues values = new ContentValues();
            values.put("fileLength", totalCount * singleLength);
            DataSupport.updateAll(LoadRecordBean.class, values, "videoId=?", videoId);
        }
    }
    public int getM3u8LoadState(String videoId) {
        int loadState = DownloadState.WAIT;
        List<LoadRecordBean> loadM3u8Files = DataSupport.select("finishState","totalTsCount", "loadTsCount").where("videoId = ?",
                videoId)
                .find(LoadRecordBean.class);
        if (loadM3u8Files.size() > 0)
            return  loadM3u8Files.get(0).getFinishState();
        return  loadState;
    }
    public void updateM3u8LoadState(String videoId, int finishState) {
        if (finishState == DownloadState.FINISH){
            //删除ts文件
            deleteLoadTsFiles(videoId);
        }
        ContentValues values = new ContentValues();
        values.put("finishState", finishState);
        DataSupport.updateAll(LoadRecordBean.class, values, "videoId=?", videoId);
    }
    public void adM3u8FileLoadTsCount(String videoId) {
        List<LoadRecordBean> loadM3u8Files = DataSupport.where("videoId = ?",
                videoId)
                .find(LoadRecordBean.class);
        int loadCount = 0;
        if (loadM3u8Files.size()>0){
            loadCount = loadM3u8Files.get(0).getLoadTsCount();
        }
        loadCount++;
        ContentValues values = new ContentValues();
        values.put("loadTsCount", loadCount);
        DataSupport.updateAll(LoadRecordBean.class, values, "videoId=?", videoId);
    }
    public void updateM3u8FileLoadLength(String videoId,long loadLength) {
        ContentValues values = new ContentValues();
        values.put("loadLength", loadLength);
        DataSupport.updateAll(LoadRecordBean.class, values, "videoId=?", videoId);
    }
    /********************数据处理end********************/


}
